package com.tjb.reggie.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import com.tjb.reggie.common.BaseContext;
import com.tjb.reggie.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author tjb
 * @version 1.0
 * @date 2022/8/24 20:13
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的路径
        String requestURI = request.getRequestURI();
        log.info(requestURI);
        //定义不需要进行处理的请求路径
        String[] urls = new String[]{
          "/employee/login",
          "/backend/**",
          "/front/**",
          "/common/**",
          "/user/sendMsg",
          "/user/login",
          "/doc.html",
          "/webjars/**",
          "/swagger-resources",
          "/v2/api-docs"
        };
        //2、判断本次请求是否需要进行处理
        boolean check = check(urls, requestURI);
        //3、如果不需要进行处理，则进行放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //4.1、判断登录状态，如果已经登录，则进行放行,网页端
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null){
            BaseContext.setCurrentUserId((Long)employee);
            filterChain.doFilter(request,response);
            return;
        }
        //4.2、判断登录状态，如果已经登录，则进行放行,移动端
        Object user = request.getSession().getAttribute("user");
        if (user != null){
            BaseContext.setCurrentUserId((Long)user);
            filterChain.doFilter(request,response);
            return;
        }
        //5、如果未登录，则返回为登录
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean check(String[] urls, String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
